package org.example.leetCode;

/**
 * @author Administrator
 */
public class Exist {
    public boolean exist(char[][] board, String word) {
        if (board.length == 0 || board[0].length == 0 || word == null) {
            return false;
        }
        char[] chars = word.toCharArray();
        boolean[][] bool = new boolean[board.length][board[0].length];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, chars, i, j, bool, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, char[] chars, int i, int j, boolean[][] bool, int start) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || chars[start] != board[i][j] || bool[i][j]) {
            return false;
        }
        if (start == chars.length - 1) {
            return true;
        }

        bool[i][j] = true;
        boolean ans = false;

        ans = dfs(board, chars, i + 1, j, bool, start + 1)
                || dfs(board, chars, i - 1, j, bool, start + 1)
                || dfs(board, chars, i, j + 1, bool, start + 1)
                || dfs(board, chars, i, j - 1, bool, start + 1);

        bool[i][j] = false;
        return ans;
    }
}
